import axios from 'axios'
import { Message } from 'element-ui'
import Variables from './variables'
// import store from '../store'
import { getToken, removeToken,
  getAuthUserInfo, removeAuthUserInfo,
  getInitUser, removeInitUser,
 } from '@/utils/auth'
import { pwLogin } from '@/api/login'
// import router from '../router'

  // create an axios instance
  const service = axios.create({
    baseURL: Variables.URL.baseURL, // api 的 base_url
    timeout: 10000,
  })


  // 设置请求头
  axios.defaults.headers.post['Content-Type'] = 'application/json';
  axios.defaults.headers.common['Authorization'] = Variables.VAR.defaultToken;

  // 拦截请求头
  service.interceptors.request.use(
    config => {
      config.headers['source'] = 'mall';
      config.headers['Authorization'] = Variables.VAR.defaultToken;

      if (getToken()) {
        if(config.url.indexOf("/auth/login") != -1){
          config.headers['Authorization'] = Variables.VAR.defaultToken
        }else{
          config.headers['Authorization'] = getToken()
        }
        config.headers['userId'] = JSON.parse(getInitUser()).userId;
        config.headers['userName'] = JSON.parse(getInitUser()).username;
      }
      return config
    },
    error => {
      Promise.reject(error)
    }
  )


  // 拦截请求返回数据，将14位及以上的数字number转成string类型
  service.defaults.transformResponse = [function (data) {
    if (typeof data === 'string') {
      try {
        let d = data;
        let array = d.match(/:\d{14}\d*/g);
        if (array === null) {
          data = JSON.parse(data);
          return data
        }
        for (let i = 0; i < array.length; i++) {
          let str = array[i];

          let number = str.replace(":", "");
          d = d.replace(str, ':"' + number + '"');
        }
        data = JSON.parse(d)
      } catch (e) { /* Ignore */
      }
    }
    return data;
  }];

  // 拦截实体
  service.interceptors.response.use(
    response => {
      const res = response.data
      if (res.code === 401) {
        if(process.browser){
          // 当前的url
          var routePath = window.location.pathname;
          routePath = routePath.replace('/mallplus', '');
          if(routePath == '/login'){
            Message({ message: res.msg, type: 'error' })
          }else{
            removeToken()
            removeAuthUserInfo()
            window.location.href = '/mallplus/login?redirect='+escape(routePath)
              // router.push('/login?redirect='+escape(router.history.current.fullPath))
          }
        }
      }else if(res.code !== 20000 && res.code !== 200 && res.code != 4041001){
        //debugger;
        Message({ message: res.msg, type: 'error' })
        return Promise.reject('error')
      } else {
        return res
      }
    },
    error => {
      return Promise.reject(error)
    }
  )


export default service
